<?php
/**
 * PayPal_Lib Controller Class (Paypal IPN Class)
 *
 * Paypal controller that provides functionality to the creation for PayPal forms, 
 * submissions, success and cancel requests, as well as IPN responses.
 *
 * The class requires the use of the PayPal_Lib library and config files.
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Commerce
 * @author      Ran Aroussi <ran@aroussi.com>
 * @copyright   Copyright (c) 2006, http://aroussi.com/ci/
 *
 */

class Paypal extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->library('paypal_lib');
		
	}
	
	function index()
	{
		log_message("info","hello");
				
		$this->form();
	}
	
	function form()
	{
		
		$this->load->library('paypal_lib');
		$this->paypal_lib->add_field('business', 'colu85@yahoo.com');
	    $this->paypal_lib->add_field('return', base_url('paypal/success'));
	    $this->paypal_lib->add_field('cancel_return', base_url('paypal/cancel'));
	    $this->paypal_lib->add_field('notify_url', base_url('paypal/ipn')); // <-- IPN url
	    $this->paypal_lib->add_field('custom', '1234567890'); // <-- Verify return

	    $this->paypal_lib->add_field('item_name', 'Paypal Test Transaction');
	    $this->paypal_lib->add_field('item_number', '6941');
	    $this->paypal_lib->add_field('amount', '197');

		// if you want an image button use this:
		$this->paypal_lib->image('btn_paynowCC_LG.gif');
		
		// otherwise, don't write anything or (if you want to 
		// change the default button text), write this:
		// $this->paypal_lib->button('Click to Pay!');
	    $data['paypal_form'] = $this->paypal_lib->paypal_form();
		$this->load->view('paypal/form', $data);
        
	}

	function auto_form()
	{
		$this->paypal_lib->add_field('business', 'PAYPAL@EMAIL.COM');
	    $this->paypal_lib->add_field('return', site_url('paypal/success'));
	    $this->paypal_lib->add_field('cancel_return', site_url('paypal/cancel'));
	    $this->paypal_lib->add_field('notify_url', site_url('paypal/ipn')); // <-- IPN url
	    $this->paypal_lib->add_field('custom', '1234567890'); // <-- Verify return

	    $this->paypal_lib->add_field('item_name', 'Paypal Test Transaction');
	    $this->paypal_lib->add_field('item_number', '6941');
	    $this->paypal_lib->add_field('amount', '197');

	    $this->paypal_lib->paypal_auto_form();
	}
	function cancel()
	{
		$this->load->view('paypal/cancel');
	}
	
	function success()
	{
		// This is where you would probably want to thank the user for their order
		// or what have you.  The order information at this point is in POST 
		// variables.  However, you don't want to "process" the order until you
		// get validation from the IPN.  That's where you would have the code to
		// email an admin, update the database with payment status, activate a
		// membership, etc.
	
		// You could also simply re-direct them to another page, or your own 
		// order status page which presents the user with the status of their
		// order based on a database (which can be modified with the IPN code 
		// below).

		$data['pp_info'] = $_POST;  
		$this->load->view('paypal/success', $data);
	}
	
	function ipn()
	{
		// Payment has been received and IPN is verified.  This is where you
		// update your database to activate or process the order, or setup
		// the database with the user's order details, email an administrator,
		// etc. You can access a slew of information via the ipn_data() array.
 
		// Check the paypal documentation for specifics on what information
		// is available in the IPN POST variables.  Basically, all the POST vars
		// which paypal sends, which we send back for validation, are now stored
		// in the ipn_data() array.
 
		// For this example, we'll just email ourselves ALL the data.
		$to    = 'colu85@yahoo.com';    //  your email

		if ($this->paypal_lib->validate_ipn()) 
		{
			$body  = 'An instant payment notification was successfully received from ';
			$body .= $this->paypal_lib->ipn_data['payer_email'] . ' on '.date('m/d/Y') . ' at ' . date('g:i A') . "\n\n";
			$body .= " Details:\n";

			foreach ($this->paypal_lib->ipn_data as $key=>$value)
				$body .= "\n$key: $value";
	
			// load email lib and email results
			$this->load->library('email');
			$this->email->to($to);
			$this->email->from($this->paypal_lib->ipn_data['payer_email'], $this->paypal_lib->ipn_data['payer_name']);
			$this->email->subject('CI paypal_lib IPN (Received Payment)');
			$this->email->message($body);	
			$this->email->send();
		}
	}
	function ipn1() 
    {

        $ipn_valid = $this->paypal_lib->validate_ipn();
        if ( $ipn_valid == TRUE )
        {


            /**
                Log IPN
                TODO: bunu daha guzel gozukecek sekilde yapayim ilerde.
            **/
            date_default_timezone_set('Europe/Istanbul');
            $this->load->helper('date');

            $raw = '';
            foreach ($this->paypal_lib->ipn_data as $key=>$value)
            {
                $raw .= "\n$key: $value";
            }

            $this->load->model('model_paypal');

            $data_ipn['user_id']            = $this->paypal_lib->ipn_data['custom']; /* get USER_ID from custom field. */
            $data_ipn['txn_id']             = $this->paypal_lib->ipn_data['txn_id'];
            $data_ipn['payment_status']     = $this->paypal_lib->ipn_data['payment_status'];
            $data_ipn['mc_gross']           = $this->paypal_lib->ipn_data['mc_gross'];
            $data_ipn['mc_fee']             = $this->paypal_lib->ipn_data['mc_fee'];
            $data_ipn['mc_currency']        = $this->paypal_lib->ipn_data['mc_currency'];
            $data_ipn['item_number']        = $this->paypal_lib->ipn_data['item_number'];
            $data_ipn['datetime']           = mdate( "%Y-%m-%d %H:%i:%s" );
            $data_ipn['status']             = IPN_ENTRY_AWAITING;
            $data_ipn['raw']                = $raw;

            $this->model_paypal->ipn_entry_add ( $data_ipn );



            $ipn_payment_status = $this->paypal_lib->ipn_data['payment_status'];
            if ( strtolower($ipn_payment_status) == 'pending' )
            {


                log_message('debug', 'payment status TAMAM');
                $this->load->model('model_user_premium');


                $ipn_item_number    = $this->paypal_lib->ipn_data['item_number'];
                $item_info          = $this->model_user_premium->Premium_item_info ( $ipn_item_number );

                $ipn_mc_gross       = $this->paypal_lib->ipn_data['mc_gross'];

                log_message('debug', 'Item fee: '. $item_info['item_fee'] );                

                if ( $item_info['item_fee'] == $ipn_mc_gross ) 
                {

                    log_message('debug', 'fee ile gross TAMAM');



                    $data_account['user_id']        = $data_ipn['user_id'];
                    $data_account['type']           = $item_info['item_type'];
                    $data_account['date_expire']    = date("Y-m-d", mktime(0, 0, 0, date("m") + $item_info['date_extender'], date("d"), date("y") ) ); 


                    log_message('debug', 'UserID: '.    $data_account['user_id']        );
                    log_message('debug', 'Type:'.       $data_account['type']           );
                    log_message('debug', 'Expire:'.     $data_account['date_expire']    );


                    $this->model_user_premium->Premium_membership_change( $data_ipn['user_id'], $data_account );

                }
                else
                {

                    //TODO: report eksik transaction.

                }

            }



        }
        elseif ( $ipn_valid == FALSE )
        {

            $this->load->library('email');
            $this->email->to( 'herrkaleun@pandorascode.com' );
            $this->email->subject('IPN - FAILED');
            $this->email->from( 'notify@bulusturx.com', 'PAYPAL' );
            $this->email->message('or 4 life'); 

            $this->email->send();

        }


    }

    function ipn_list()
    {
        //TODO: admin check
        $this->load->helper('form');
        $this->load->model('model_theme');

        switch ( $_SERVER['REQUEST_METHOD'] ) 
        {

            case 'GET':

                /* Theme System with Reference Variable ( first param ) */
                $this->model_theme->Theme_returnThemeInfo( $data, 'paypal' );
                $this->load->view( $data['theme_folder_vault'] . 'master-ipn_list', $data );


            break;

            case 'POST':

                $this->load->model('model_paypal');
                $user_id    = $this->input->post('user_id');
                $txn_id     = $this->input->post('txn_id');

                $list_ipn = $this->model_paypal->ipn_entry_list ( $user_id, $txn_id );

                echo '<pre>';
                print_r( $list_ipn );
                echo '</pre>';


            break;


            default:
            break;
        }


    }


    function ipn_test()
    {

        $this->load->model('model_user_premium');

        $data_account['user_id']        = 123;
        $data_account['type']           = 4;
        $data_account['date_expire']    = date("Y-m-d", mktime(0, 0, 0, date("m") + 12, date("d"), date("y") ) );

        echo '<pre>';
        print_r( $data_account );
        echo '</pre>';


        $this->model_user_premium->Premium_membership_change( 123, $data_account );

    }
	
}
?>